package com.ymsoft.myerp.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ymsoft.myerp.common.DTO;
import com.ymsoft.myerp.common.RetEnum;
import com.ymsoft.myerp.entity.Dict;
import com.ymsoft.myerp.service.IDictService;
import com.ymsoft.myerp.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import com.ymsoft.myerp.common.BaseController;

import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 * 字典表 前端控制器
 * </p>
 *
 * @author ymsoft
 * @since 2020-04-12
 */
@Controller
@RequestMapping("/myerp/dict")
public class DictController extends BaseController {
    @Autowired
    private IDictService iDictService;

    //查询全部字典、
    @RequestMapping("/list")
    @ResponseBody
    public DTO<?> list(@Valid Dict dict) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(dict.getName())){
            queryWrapper.like("name",dict.getName());
        }
        List<Dict> dicts = iDictService.list(queryWrapper);
        return DTO.retSuccess(dicts, dicts.size());
    }

    //查询全部字典、不分页
    @PostMapping("/all")
    @ResponseBody
    public DTO<?> listall(){
        List<Dict> dicts = iDictService.list();
        return DTO.retSuccess(dicts, dicts.size());
    }

    /**
     * 新增字典
     * @param dict
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public DTO<?> save(@Valid Dict dict){
        if(dict.getPid() == 0) {//顶级字典下存在相同的字典标识
            QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("name", dict.getName());
            queryWrapper.eq("pid", 0);
            int count = iDictService.count(queryWrapper);
            if(count > 0) return DTO.ret(RetEnum.RET_DICT_SAME_CODE_UNDER_SUPPER_PARENT);
        }

        boolean ok= iDictService.save(dict);
        if(ok){
            return DTO.retSuccess();
        }else {
            return DTO.retFailed();
        }
    }

    /**
     * 编辑字典
     * @param dict
     * @return
     */
    @PostMapping("/update")
    @ResponseBody
    public DTO<?> update(@Valid Dict dict){
        //限制选择自己作为父级
        if(dict.getPid() == dict.getId().intValue()) {
            return DTO.ret(RetEnum.RET_DICT_CHOOSE_SELF);
        }
        if(dict.getPid() == 0) {//顶级字典下存在相同的字典标识
            QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("name", dict.getName());
            queryWrapper.eq("pid", 0);
            queryWrapper.ne("id", dict.getId());
            int count = iDictService.count(queryWrapper);
            if(count > 0) return DTO.ret(RetEnum.RET_DICT_SAME_CODE_UNDER_SUPPER_PARENT);
        }
        //限制选择自己的子级作为父级
//        QueryWrapper<SysDict> queryWrapper1 = new QueryWrapper<>();
//        queryWrapper1.eq("pid", sysDict.getId());
//        queryWrapper1.eq("id", sysDict.getPid());
//        int count = iSysDictService.count(queryWrapper1);
//        if(count > 0) return JSON.toJSONString(ResponseEntity.ok(new Response(RetEnum.RET_SYS_DICT_CHOOSE_ChILD,null)));
        boolean ok = iDictService.updateById(dict);
        if(ok){
            return DTO.retSuccess();
        }else {
            return DTO.retFailed();
        }
    }

    /**
     * 物理删除字典
     * @param dict
     * @return
     */
    @PostMapping("/del")
    @ResponseBody
    public DTO<?> delete(@Valid Dict dict){
        //限制删除父级字典
        boolean ok= iDictService.removeById(dict.getId());
        if(ok) {
            return DTO.retSuccess();
        } else {
            return DTO.retFailed();
        }
    }

    @RequestMapping(value = "/treetable", method = RequestMethod.GET, produces = "application/json", headers = "Accept=application/json")
    @ResponseBody
    public String treetable() {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        List<Dict> dict = iDictService.list(queryWrapper);
        int count = iDictService.count();
        return JSON.toJSONString(DTO.retSuccess(dict, count));
    }

    @RequestMapping(value = "/getone/{id}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public DTO<?> getOne(@PathVariable("id") String id) {
        Dict dict = iDictService.getById(id);
        if(dict != null) {
            return DTO.retSuccess(dict);
        }
        return DTO.retFailed();
    }

    //查询全部字典
    @RequestMapping(value = "/table", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public DTO<?> table(@RequestParam(value = "name", required = false) String name,
                        @RequestParam(value = "tips", required = false) String tips){
        QueryWrapper<Dict> q1 = new QueryWrapper<>();
        q1.eq("id", 0);//总父级
        Dict parentDict = iDictService.getOne(q1);

        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        if(parentDict != null) {
            queryWrapper.in("pid", parentDict.getId(), -1);
        }
        if(StringUtils.isNotBlank(name)) {
            queryWrapper.like("name", name);
        }
        if(StringUtils.isNotBlank(tips)) {
            queryWrapper.like("tips", tips);
        }
        List<Dict> dicts= iDictService.list(queryWrapper);
        return DTO.retSuccess(dicts);
    }


    @GetMapping(value = "/get_dict_by_type/{name}", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public DTO<?> getDictByType(@PathVariable("name") String name) {
        QueryWrapper<Dict> q = new QueryWrapper<>();
        q.eq("name", name);
        List<Dict> dicts = iDictService.list(q);
        if(dicts != null) {
            return DTO.retSuccess(dicts);
        }
        return DTO.retFailed();
    }
}
